package com.fin.quant.web.controller;

import com.fin.quant.app.ai.AIService;
import com.fin.quant.app.vo.ChatRequestDto;
import com.fin.quant.app.vo.ChatResponseDto;
import com.fin.quant.app.vo.PageContext;
import com.fin.quant.domain.entity.AIUserSettingsEntity;
import com.fin.quant.domain.repository.impl.AIUserSettingsRepositoryImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

/**
 * AI助手控制器
 */
@RestController
@RequestMapping("/api/v1/ai")
@CrossOrigin(origins = "*")
@Slf4j
public class AIController {

    @Autowired
    private AIService aiService;


    @Autowired
    private AIUserSettingsRepositoryImpl userSettingsService;

    /**
     * AI聊天接口
     */
    @PostMapping("/chat")
    public ResponseEntity<ChatResponseDto> chat(@RequestBody @Valid ChatRequestDto request) {
        try {
            log.info("Received AI chat request: {}", request.getMessage());

            ChatResponseDto response = aiService.chat(request);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("AI Chat Error:", e);
            ChatResponseDto response = new ChatResponseDto(false, null, "AI服务暂时不可用，请稍后重试");
            return ResponseEntity.status(500).body(response);
        }
    }




    /**
     * 流式聊天接口 - 使用Server-Sent Events (SSE)
     */
    @PostMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.OPTIONS})
    public SseEmitter chatStream(@RequestBody ChatRequestDto requestDto) {
        return aiService.chatStream(requestDto);
    }

    @RequestMapping(value = "/chat/stream", method = RequestMethod.OPTIONS)
    public ResponseEntity<?> handlePreflight() {
        return ResponseEntity.ok()
                .header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "POST, OPTIONS")
                .header("Access-Control-Allow-Headers", "Content-Type, Accept, Cache-Control, Connection")
                .build();
    }

    /**
     * 获取用户AI设置
     */
    @GetMapping("/settings/{userId}")
    public ResponseEntity<AIUserSettingsEntity> getUserSettings(@PathVariable Long userId) {
        try {
            AIUserSettingsEntity settings = userSettingsService.getUserSettings(userId);
            return ResponseEntity.ok(settings);
        } catch (Exception e) {
            log.error("Get user settings error:", e);
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 更新用户AI设置
     */
    @PutMapping("/settings/{userId}")
    public ResponseEntity<AIUserSettingsEntity> updateUserSettings(
            @PathVariable Long userId,
            @RequestBody AIUserSettingsEntity settings) {
        try {
            AIUserSettingsEntity updatedSettings = userSettingsService.updateUserSettings(userId,
                    settings);
            return ResponseEntity.ok(updatedSettings);
        } catch (Exception e) {
            log.error("Update user settings error:", e);
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 获取建议
     */
    @PostMapping("/suggestions")
    public ResponseEntity<List<String>> getSuggestions(@RequestBody PageContext context) {
        try {
            // TODO: 实现获取建议的逻辑
            List<String> suggestions = Arrays.asList(
                    "推荐一些高股息率的股票",
                    "分析当前选中的资产",
                    "如何构建稳健的投资组合？");
            return ResponseEntity.ok(suggestions);
        } catch (Exception e) {
            log.error("Get suggestions error:", e);
            return ResponseEntity.status(500).build();
        }
    }


}
